#!/bin/bash

function kill_sub () {
	echo "Killing pid: $1"
	kill -TERM "$1" 2>/dev/null
	exit 1
}

if [ $# -le 0 ]
then
	echo "Usage: run_task [your full command]"
	exit 1
fi

mkdir -p /run/record
tmpfile=$(mktemp)
export TZ=Asia/Shanghai
starttime=$(date "+%H_%M_%S_%N")
echo "Now running the command in the command mode." >> ${tmpfile}
fullpath=$(which $1)
echo "Command path: $fullpath" >> ${tmpfile}
echo "MD5SUM: $(md5sum $fullpath)" >> ${tmpfile}
echo "Start time: ${starttime}" >> ${tmpfile}
echo "==========================" >> ${tmpfile}
cmd=$@ 
echo "Cmd: \" ${cmd} \". Now start" >> ${tmpfile}
stdbuf --output=L --error=L ${cmd} 2>&1 | tee -a ${tmpfile} &
pid="$!"
trap "{ kill_sub $pid; }" SIGINT
wait ${pid}
st=$?
stoptime=$(date "+%H_%M_%S_%N")
echo "==========================" >> ${tmpfile}
echo "Stop time: ${stoptime}" >> ${tmpfile}
echo "Status: ${st}" >> ${tmpfile}
savefile=/run/record/${pid}_${starttime}.run
mv ${tmpfile} ${savefile}
echo "============================"
echo "Command finished successfully. The log file is ${savefile}"
echo "If you want this result, run:"
echo "cp ${savefile} /your/desired/path"

